package cn.zhoutao.org.service.impl;

import cn.zhoutao.basic.service.impl.BaseServiceImpl;
import cn.zhoutao.org.domain.Department;
import cn.zhoutao.org.mapper.DepartmentMapper;
import cn.zhoutao.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    //1.基础的CRUD实现通过继承BaseServiceImpl 得到 但是，如果基本的实现满足不了要求，请你自己覆写

    //2.特殊的接口实现在这里自己写

    /**
     * 新增一条数据
     * @param department
     */
    @Override
    @Transactional
    public void save(Department department) {
        departmentMapper.save(department);//返回自增id
        this.update(department);
    }

    /**
     * 修改一条数据
     * @param department
     */
    @Override
    @Transactional
    public void update(Department department) {
        String dirPath = "";
        if(department.getParent()==null){
            //1.新增的是顶级部门   /自己id
            dirPath = "/" +department.getId();
        }else{
            //2.新增的是非顶级部门  找到父级目录
            Department parent = departmentMapper.loadById(department.getParent().getId());
            dirPath = parent.getDirPath() + "/" + department.getId();
        }
        department.setDirPath(dirPath);
        departmentMapper.update(department);
    }
     /** 方案四：无线级数
     *    1.一次性查询出所有数据，放到内存 all
     *    2.从所有数据中找出第一层级 firstCourseType   我们需要返回的最外数据
     *    3.只要不是第一层级的，找自己的上级，并将自己放入上级的children
     *
     */
    @Override
    public List<Department> queryTree() {
        // 1.一次性查询出所有数据，放到内存 all
        List<Department> departments = departmentMapper.loadAll();
        //为了后面找自己的父亲，我们这里可以把整体的部门数据，转换一份成Map<id,department>
        HashMap<Long, Department> allDepts = new HashMap<>();
        for (Department department : departments) {
            allDepts.put(department.getId(), department);//拿到key  和 value
        }
        List<Department> firstDepts = new ArrayList<>();//遍历最上层级
        for (Department tmp : departments) {
            if (tmp.getParent_id() == null) {//如果没有最上层  那么自己就是最上层
                firstDepts.add(tmp);//（最上层的自己）将自己封装到tmp中
            } else {
                // 3.只要不是第一层级的，找自己的上级，并将自己放入上级的children中
                Department parent = allDepts.get(tmp.getParent_id());
                if (parent != null) {
                    parent.getChildren().add(tmp);
                }
            }
        }
        return firstDepts;

    }
}
